import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateBlogCategoryDto } from './dto/create-blog_category.dto';
import { UpdateBlogCategoryDto } from './dto/update-blog_category.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { BlogCategory } from './entities/blog_category.entity';
import { Repository } from 'typeorm';

@Injectable()
export class BlogCategoryService {
  @InjectRepository(BlogCategory)
  private blogCategoryRepository: Repository<BlogCategory>

  async createCategory(createBlogCategoryDto: CreateBlogCategoryDto) {
    const category = new BlogCategory()
    category.value = createBlogCategoryDto.value
    return await this.blogCategoryRepository.save(category)
  }

  async findAll() {
    return await this.blogCategoryRepository.find()
  }

  async findOneById(id: number) {
    const category =  await this.blogCategoryRepository.findOneBy({
      id: id
    })
    if(!category) {
      throw new HttpException('没有找到此分类', HttpStatus.BAD_REQUEST)
    }
    return category
  }

  async update(updateBlogCategoryDto: UpdateBlogCategoryDto) {
    const category = await this.findOneById(updateBlogCategoryDto.id)
    category.value = updateBlogCategoryDto.value
    try {
      const updateCategory = await this.blogCategoryRepository.save(category);
      return updateCategory
    } catch (error) {
      throw new HttpException('更新失败', HttpStatus.BAD_REQUEST)
    } 
  }

  removeById(id: number) {
    return this.blogCategoryRepository.delete(id);
  }
}
